package com.thinkTank.oa.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
public class FileUtils {

	public static final int BUFFER_SIZE = 4096;
	/**
	 * 格式化当前时间
	 * 
	 * @return 1921-05-01 13:12:12
	 */
	public static String getCurrentDateTime(String pattern) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(pattern);
		return sd.format(new java.util.Date());
	}
	/***
	 * 
	 * @param fileType 上传的文件类型  是person 还是 conf 还是  but对接详情
	 * @param fileName 上传的文件名字
	 * @return 唯一的一个文件名字
	 * @author dq
	 * @date 2018-08-21
	 */
	public  static String  generateFileName(String fileType,String fileName){
		int random = new Random().nextInt(10000); // 保证4位数
		if (random <= 999) {
			random = random + 1000;
		}
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return fileType + "-" + getCurrentDateTime("yyyyMMdd-HHmmss")  + "-" + random + extension;
	}
	public static String toString(InputStream in, String encoding) {
		BufferedReader reader = null;
		StringBuilder sb = null;
		try {
			reader = new BufferedReader(new InputStreamReader(in, encoding));
			sb = new StringBuilder();
			int c;
			c = reader.read();
			while (c != -1) {
				sb.append((char) c);
				c = reader.read();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			FileUtils.closeQuietly(reader);
		}
		return sb.toString();
	}
	
	public static StringBuilder readFileToString(String path) {
		BufferedReader reader = null;
		StringBuilder sb = null;
		try {
			reader = new BufferedReader(new FileReader(path));
			sb = new StringBuilder();
			String text = null;
			while((text = reader.readLine()) != null){
				sb.append(text + "\n");
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			FileUtils.closeQuietly(reader);
		}
		return sb;
	}
	
	public static StringBuilder readLogToString(String path) {
		BufferedReader reader = null;
		StringBuilder sb = null;
		try {
			reader = new BufferedReader(new FileReader(path));
			sb = new StringBuilder();
			int c;
			c = reader.read();
			while (c != -1) {
				if(c == 32){ // 空格
					sb.append("&nbsp;");
				}else if(c == 9){ // /t 
					sb.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
				}else if(c == 10){
					sb.append("<br/>");
				}else{
					sb.append((char)c);
				}
				c = reader.read();
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			FileUtils.closeQuietly(reader);
		}
		return sb;
	}

	
	public static StringBuilder readFileToString(String path, String encoding) {
		BufferedReader reader = null;
		StringBuilder sb = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(path), encoding));
			sb = new StringBuilder();
			int c;
			c = reader.read();
			while (c != -1) {
				sb.append((char) c);
				c = reader.read();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			FileUtils.closeQuietly(reader);
		}
		return sb;
	}
	
	public static List<String> readFileFolderlist(String path){
		try {
			File folder = new File(path);
			if(!folder.exists()){
				return null;
			}
			File[] files = folder.listFiles();
			
			if(files.length == 0){
				return null;
			}
			
			List<String> filelist = new ArrayList<String>();
			for (int i = 0; i < files.length; i++) {
				if(!files[i].isDirectory()){
					filelist.add(files[i].getName());
				}
			}
			return filelist;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	 
	
	public static void saveStringToFile(String path, String content) {
		saveStringToFile(path, content, false);
	}
	
	public static void saveStringToFile(String path, String content, boolean append) {
		makeDir(path);
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(path, append));
			writer.write(content);
		} catch (Exception e) {
//			throw new RuntimeException(e);
		} finally {
			FileUtils.closeQuietly(writer);
		}
	}
	
	
	public static boolean makeDir(String path) {
		return makeDir(new File(path));
	}
	
	public static boolean makeDir(File file) {
		if (file.isDirectory()) {
		} else {
			file = file.getParentFile();
		}
		if (!file.exists()) {
			return file.mkdirs();
		}
		return false;
	}
	
	
	public static void copy(String fromPath, String toPath) {
		makeDir(toPath);
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(
					fromPath));
			OutputStream os = new BufferedOutputStream(new FileOutputStream(
					toPath));
			copy(is, os);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void copy(File fromPath, File toPath) {
		makeDir(toPath);
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(fromPath));
			OutputStream os = new BufferedOutputStream(new FileOutputStream(toPath));
			copy(is, os);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static int copy(InputStream in, OutputStream out) throws IOException {
		try {
			int byteCount = 0;
			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			while ((bytesRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesRead);
				byteCount += bytesRead;
			}
			out.flush();
			return byteCount;
		} finally {
			FileUtils.closeQuietly(in);
			FileUtils.closeQuietly(out);
		}
	}
	
	public static boolean deleteFileOrFolder(File file) {
//		if (!file.exists()) {
//			throw new java.lang.IllegalArgumentException("file not found");
//		}
//		File[] childs = file.listFiles();
//		if (childs == null || childs.length < 1) {// element
//		} else {// not element
//			for (File child : childs) {
//				deleteFileOrFolder(child);
//			}
//		}
//		return file.delete();
		return true;
	}
	
	
	public static void closeQuietly(Reader input) {
		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}

	public static void closeQuietly(Writer output) {
		try {
			if (output != null) {
				output.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}

	public static void closeQuietly(InputStream input) {
		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}

	public static void closeQuietly(OutputStream output) {
		try {
			if (output != null) {
				output.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	public static List<String> getTxtFileList(String file){
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		try{
			File f = new File(file);
			if(f.exists()){
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(f),"utf-8"));
				String str;
				while ((str = reader.readLine()) != null) {
					list.add(str.trim());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 * 上传文件工具类
	 * @param file  
	 * @param filePath 文件路径
	 * @param fileName 文件名字
	 * @throws Exception
	 */
	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath); 
        //如果路径不存在就创建一个
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        //保存文件
        out.write(file);
        //关闭流
        out.flush();
        out.close();
    }
	
	/**
	 * 专用于springmvc的文件上传，调用时不用判断文件是否为空
	 * @author pdz
	 * @date 2018年8月27日
	 * @param path 存储上传文件的文件夹
	 * @param file 上传的文件
	 * @param fileType 见generateFileName方法
	 * @return 返回新文件名，文件不存在返回null
	 */
	public static String transferTo(String path, MultipartFile file, String fileType) {
	    if (file != null && !file.isEmpty()) {
	        String generateFileName = generateFileName(fileType, file.getOriginalFilename());
	        try {
	            File dest = new File(path, generateFileName);
	            if (!dest.getParentFile().exists())
	                dest.getParentFile().mkdirs();
                file.transferTo(dest);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return generateFileName;
	    }
        return null;
	}
	
	/**
	 * 下载文件
	 * @author pdz
	 * @date 2019年1月24日
	 * @param file
	 * @param response
	 * @throws Exception
	 */
	public static void downLoad(File file, HttpServletResponse response) throws Exception {
		response.setContentType("text/html,charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		try {
			FileInputStream in = new FileInputStream(file);
			OutputStream fos = response.getOutputStream();
			response.reset();
			response.setContentType("application/x-download");
			response.setHeader("Content-disposition", "attachment;filename=" + file.getName());
			byte[] b = new byte[2048];
			int read;
			while ((read = in.read(b)) != -1) {
				fos.write(b, 0, read);
			}
			fos.flush();
			in.close();
			fos.close();
		} catch (Exception e) {
			e.getMessage();
		}
	}
}
